import { BlankLayout } from '@/components/layouts'

// 格式化菜单
const formatMenu = function(arr) {
  for (let i = 0; i < arr.length; i++) {
    // 先获取菜单下的子菜单
    var children = arr[i].childMenu ? arr[i].childMenu : []
    // 格式化菜单。将其转变成可以用的路由
    arr[i] = getWholeRouter(arr[i])
    formatMenu(children)
    if (children.length > 0) {
      // 如果原先的菜单下已经存在有子菜单就合并
      if (arr[i].children && arr[i].children.length > 0) {
        arr[i].children.concat(children)
      } else {
        arr[i].children = children
      }
    }
  }
}

const getWholeRouter = function(routers, item) {
  if (item.path === null || item.path === undefined || item.path === 'null' || item.path === 'undefined') {
    item.path = ''
  }
  var routeritem = routers.filter(v => {
    return v.path === item.path
  })
  if (routeritem.length === 0) {
    // return this.$message.error('传入的菜单地址有误')
  } else {
    let children = routeritem[0].children
    let component = routeritem[0].component
    // 为了防止源数据被污染,copy一份数据
    let menu = JSON.parse(JSON.stringify(routeritem[0]))
    menu.meta.key = item.key
    menu.meta.title = item.menuName
    menu.meta.icon = item.icon
    menu.children = children
    // 如果是空的就将空白页面作为该页面的components
    if (menu.path === '') {
      menu.component = BlankLayout
      // menu.path = 'otherPath123'
    } else {
      menu.component = component
    }
    menu.hidden = false
    return menu
  }
}

// 获取第一个需要跳转的地址
const getFirstRouter = function(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].path !== '' && arr[i].path !== null && arr[i].path !== undefined) {
      return arr[i].path
    }
    if (arr[i].childMenu && arr[i].childMenu.length > 0) {
      if (getFirstRouter(arr[i].childMenu)) {
        return getFirstRouter(arr[i].childMenu)
      }
    }
  }
}

export {
  formatMenu,
  getWholeRouter,
  getFirstRouter
}